{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c261e5f4-17a8-40da-beb9-599f1717e0fe",
   "metadata": {},
   "source": [
    "### 1. 安装HuggingFace 并下载模型到本地"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "02785614-9268-41c8-85a5-d579490edbbf",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple\n",
      "Requirement already satisfied: sagemaker in /opt/conda/lib/python3.10/site-packages (2.184.0)\n",
      "Collecting sagemaker\n",
      "  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/a5/94/7a2bba5c50316a630ad49e11540a82c938c146593601d1af1e3610cccc03/sagemaker-2.191.0.tar.gz (896 kB)\n",
      "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m896.6/896.6 kB\u001b[0m \u001b[31m4.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0m\n",
      "\u001b[?25h  Preparing metadata (setup.py) ... \u001b[?25ldone\n",
      "\u001b[?25hRequirement already satisfied: attrs<24,>=23.1.0 in /opt/conda/lib/python3.10/site-packages (from sagemaker) (23.1.0)\n",
      "Requirement already satisfied: boto3<2.0,>=1.26.131 in /opt/conda/lib/python3.10/site-packages (from sagemaker) (1.28.42)\n",
      "Requirement already satisfied: cloudpickle==2.2.1 in /opt/conda/lib/python3.10/site-packages (from sagemaker) (2.2.1)\n",
      "Requirement already satisfied: google-pasta in /opt/conda/lib/python3.10/site-packages (from sagemaker) (0.2.0)\n",
      "Requirement already satisfied: numpy<2.0,>=1.9.0 in /opt/conda/lib/python3.10/site-packages (from sagemaker) (1.25.2)\n",
      "Requirement already satisfied: protobuf<5.0,>=3.12 in /opt/conda/lib/python3.10/site-packages (from sagemaker) (4.24.2)\n",
      "Requirement already satisfied: smdebug_rulesconfig==1.0.1 in /opt/conda/lib/python3.10/site-packages (from sagemaker) (1.0.1)\n",
      "Requirement already satisfied: importlib-metadata<7.0,>=1.4.0 in /opt/conda/lib/python3.10/site-packages (from sagemaker) (4.11.3)\n",
      "Requirement already satisfied: packaging>=20.0 in /opt/conda/lib/python3.10/site-packages (from sagemaker) (21.3)\n",
      "Requirement already satisfied: pandas in /opt/conda/lib/python3.10/site-packages (from sagemaker) (1.4.4)\n",
      "Requirement already satisfied: pathos in /opt/conda/lib/python3.10/site-packages (from sagemaker) (0.3.1)\n",
      "Requirement already satisfied: schema in /opt/conda/lib/python3.10/site-packages (from sagemaker) (0.7.5)\n",
      "Requirement already satisfied: PyYAML~=6.0 in /opt/conda/lib/python3.10/site-packages/PyYAML-6.0-py3.10-linux-x86_64.egg (from sagemaker) (6.0)\n",
      "Requirement already satisfied: jsonschema in /opt/conda/lib/python3.10/site-packages (from sagemaker) (4.19.0)\n",
      "Requirement already satisfied: platformdirs in /opt/conda/lib/python3.10/site-packages (from sagemaker) (2.5.2)\n",
      "Requirement already satisfied: tblib==1.7.0 in /opt/conda/lib/python3.10/site-packages (from sagemaker) (1.7.0)\n",
      "Requirement already satisfied: botocore<1.32.0,>=1.31.42 in /opt/conda/lib/python3.10/site-packages (from boto3<2.0,>=1.26.131->sagemaker) (1.31.42)\n",
      "Requirement already satisfied: jmespath<2.0.0,>=0.7.1 in /opt/conda/lib/python3.10/site-packages (from boto3<2.0,>=1.26.131->sagemaker) (0.10.0)\n",
      "Requirement already satisfied: s3transfer<0.7.0,>=0.6.0 in /opt/conda/lib/python3.10/site-packages (from boto3<2.0,>=1.26.131->sagemaker) (0.6.0)\n",
      "Requirement already satisfied: zipp>=0.5 in /opt/conda/lib/python3.10/site-packages (from importlib-metadata<7.0,>=1.4.0->sagemaker) (3.8.0)\n",
      "Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /opt/conda/lib/python3.10/site-packages (from packaging>=20.0->sagemaker) (3.0.9)\n",
      "Requirement already satisfied: six in /opt/conda/lib/python3.10/site-packages (from google-pasta->sagemaker) (1.16.0)\n",
      "Requirement already satisfied: jsonschema-specifications>=2023.03.6 in /opt/conda/lib/python3.10/site-packages (from jsonschema->sagemaker) (2023.7.1)\n",
      "Requirement already satisfied: referencing>=0.28.4 in /opt/conda/lib/python3.10/site-packages (from jsonschema->sagemaker) (0.30.2)\n",
      "Requirement already satisfied: rpds-py>=0.7.1 in /opt/conda/lib/python3.10/site-packages (from jsonschema->sagemaker) (0.10.2)\n",
      "Requirement already satisfied: python-dateutil>=2.8.1 in /opt/conda/lib/python3.10/site-packages (from pandas->sagemaker) (2.8.2)\n",
      "Requirement already satisfied: pytz>=2020.1 in /opt/conda/lib/python3.10/site-packages (from pandas->sagemaker) (2022.1)\n",
      "Requirement already satisfied: ppft>=1.7.6.7 in /opt/conda/lib/python3.10/site-packages (from pathos->sagemaker) (1.7.6.7)\n",
      "Requirement already satisfied: dill>=0.3.7 in /opt/conda/lib/python3.10/site-packages (from pathos->sagemaker) (0.3.7)\n",
      "Requirement already satisfied: pox>=0.3.3 in /opt/conda/lib/python3.10/site-packages (from pathos->sagemaker) (0.3.3)\n",
      "Requirement already satisfied: multiprocess>=0.70.15 in /opt/conda/lib/python3.10/site-packages (from pathos->sagemaker) (0.70.15)\n",
      "Requirement already satisfied: contextlib2>=0.5.5 in /opt/conda/lib/python3.10/site-packages (from schema->sagemaker) (21.6.0)\n",
      "Collecting urllib3<1.27,>=1.25.4 (from botocore<1.32.0,>=1.31.42->boto3<2.0,>=1.26.131->sagemaker)\n",
      "  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/48/fe/a5c6cc46e9fe9171d7ecf0f33ee7aae14642f8d74baa7af4d7840f9358be/urllib3-1.26.17-py2.py3-none-any.whl (143 kB)\n",
      "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m143.4/143.4 kB\u001b[0m \u001b[31m2.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m\n",
      "\u001b[?25hBuilding wheels for collected packages: sagemaker\n",
      "  Building wheel for sagemaker (setup.py) ... \u001b[?25ldone\n",
      "\u001b[?25h  Created wheel for sagemaker: filename=sagemaker-2.191.0-py2.py3-none-any.whl size=1197714 sha256=196acff84df6b3641b89640a11c65eac3a93cbecdf2ee229e49b804cd37fcae9\n",
      "  Stored in directory: /root/.cache/pip/wheels/44/fa/ba/c5c651d1e70cb679f61a537dc1f4b6f5c41f02cad7cf51a879\n",
      "Successfully built sagemaker\n",
      "Installing collected packages: urllib3, sagemaker\n",
      "  Attempting uninstall: urllib3\n",
      "    Found existing installation: urllib3 2.0.4\n",
      "    Uninstalling urllib3-2.0.4:\n",
      "      Successfully uninstalled urllib3-2.0.4\n",
      "  Attempting uninstall: sagemaker\n",
      "    Found existing installation: sagemaker 2.184.0\n",
      "    Uninstalling sagemaker-2.184.0:\n",
      "      Successfully uninstalled sagemaker-2.184.0\n",
      "\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n",
      "distributed 2022.7.0 requires tornado<6.2,>=6.0.3, but you have tornado 6.3.3 which is incompatible.\u001b[0m\u001b[31m\n",
      "\u001b[0mSuccessfully installed sagemaker-2.191.0 urllib3-1.26.17\n",
      "\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m"
     ]
    }
   ],
   "source": [
    "!pip install huggingface-hub -Uqq -i https://pypi.tuna.tsinghua.edu.cn/simple\n",
    "!pip install modelscope -i https://pypi.tuna.tsinghua.edu.cn/simple\n",
    "!pip install -U sagemaker -i https://pypi.tuna.tsinghua.edu.cn/simple"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "0ba24701-47db-4107-9a6c-1667038d0054",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "!rm -rf ./LLM_qwen_int4_model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "9e6bd7ee-16a3-4f5a-8857-8bbba83eb9e7",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from huggingface_hub import snapshot_download\n",
    "from pathlib import Path\n",
    "local_model_path = Path(\"./LLM_qwen_int4_model\")\n",
    "local_model_path.mkdir(exist_ok=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c3469632-4174-4df4-a7d1-ef167561c626",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# model_name = \"Qwen/Qwen-7B-Chat-Int4\"\n",
    "# commit_hash = \"b725fe596dce755fe717c5b15e5c8243d5474f66\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "94e8abc5-a58e-40e2-b1e6-fbf48307c716",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "2d994b608cf84c8db4b375798c0bacc6",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Fetching 26 files:   0%|          | 0/26 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "a8d046fdb37246b98d09bb26eb2e52ce",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)/assets/cli_demo.gif:   0%|          | 0.00/249k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "930bcf993a144568877eca64fbc7c6ff",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)43d5474f66/README.md:   0%|          | 0.00/28.1k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8fa29daa318242878bb9472e96039dbd",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)74f66/.gitattributes:   0%|          | 0.00/1.59k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "46c2a125b61e4a5786d3d4983007f1d7",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)8243d5474f66/LICENSE:   0%|          | 0.00/6.90k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "f049d08e7d974002a368bd32ef17b4d0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)ter_showcase_001.jpg:   0%|          | 0.00/138k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "542d1b9db65343c7b1c2c71ec18501ba",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)act_showcase_001.png:   0%|          | 0.00/309k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "befdf7c0b9b94f2eaddc322bbf18323c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)c8243d5474f66/NOTICE:   0%|          | 0.00/2.70k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "7e87419da5ab4230955ed2b1f592bbcf",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)66/assets/wechat.png:   0%|          | 0.00/73.0k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "95bcf42bd84e465db541a074f94cee25",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)4f66/assets/logo.jpg:   0%|          | 0.00/65.1k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "acc2946de9114b2ea9aaa8ddbcd8f019",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)act_showcase_002.png:   0%|          | 0.00/630k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "40c924122f6b4f9a9af9a2f952430605",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)utogptq_cuda_256.cpp:   0%|          | 0.00/8.40k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "78f014bc2b9b47228d958a81f0fba90e",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)q_cuda_kernel_256.cu:   0%|          | 0.00/52.0k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "91b10b9ab94b4410b01a0c37ba5e724d",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)onfiguration_qwen.py:   0%|          | 0.00/2.35k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e3871944f31f4f5d88c7e1de0381a2d7",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)d5474f66/config.json:   0%|          | 0.00/1.20k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "78046243b0b24cab98eed0e8bea10571",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)74f66/cpp_kernels.py:   0%|          | 0.00/1.92k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "49f16003edca498b95572a1ff97cae82",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)of-00003.safetensors:   0%|          | 0.00/2.05G [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c41dd79ab0714a68a17c87ba43380e3c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)of-00003.safetensors:   0%|          | 0.00/1.77G [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "70626af7fec34a0ea19778983b5b1615",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)of-00003.safetensors:   0%|          | 0.00/2.04G [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9bf3bb401047400abdccfc6eedece4f0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)neration_config.json:   0%|          | 0.00/239 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "517d807d66e54041b9b6e4232019f2f0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)fetensors.index.json:   0%|          | 0.00/65.7k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5a92cf83cb1e4e49a955286662148b8c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)f66/modeling_qwen.py:   0%|          | 0.00/56.9k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ade0e97a624d4e4d8250713333bec8a9",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)474f66/qwen.tiktoken:   0%|          | 0.00/2.56M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8e1710e2ad744b008627db2b0d36a2cb",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)_generation_utils.py:   0%|          | 0.00/14.6k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "3043733e33d74306bf46704634a148de",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)quantize_config.json:   0%|          | 0.00/214 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9ab15d46e4884d66803bd7fed7326408",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)tokenization_qwen.py:   0%|          | 0.00/8.44k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "51370457a54545d5918a822228e81748",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Downloading (…)okenizer_config.json:   0%|          | 0.00/193 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "'LLM_qwen_int4_model/models--Qwen--Qwen-7B-Chat-Int4/snapshots/b725fe596dce755fe717c5b15e5c8243d5474f66'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# snapshot_download(repo_id=model_name, revision=commit_hash, cache_dir=local_model_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99a644dd-d048-4629-b51c-38913b9a684f",
   "metadata": {},
   "source": [
    "## 如果是中国区，从modelscope下载比较快"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "9f191be3-111b-41eb-a858-a12012c3bee6",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2023-10-08 08:30:40,070 - modelscope - INFO - Use user-specified model revision: v1.1.4\n",
      "Downloading: 100%|██████████| 8.21k/8.21k [00:00<00:00, 14.0MB/s]\n",
      "Downloading: 100%|██████████| 50.8k/50.8k [00:00<00:00, 756kB/s]\n",
      "Downloading: 100%|██████████| 1.17k/1.17k [00:00<00:00, 6.71MB/s]\n",
      "Downloading: 100%|██████████| 2.29k/2.29k [00:00<00:00, 12.9MB/s]\n",
      "Downloading: 100%|██████████| 1.88k/1.88k [00:00<00:00, 10.6MB/s]\n",
      "Downloading: 100%|██████████| 239/239 [00:00<00:00, 1.49MB/s]\n",
      "Downloading: 100%|██████████| 6.73k/6.73k [00:00<00:00, 1.64MB/s]\n",
      "Downloading: 100%|█████████▉| 1.90G/1.90G [00:25<00:00, 79.3MB/s]\n",
      "Downloading: 100%|█████████▉| 1.91G/1.91G [00:26<00:00, 78.3MB/s]\n",
      "Downloading: 100%|█████████▉| 1.65G/1.65G [00:21<00:00, 83.4MB/s]\n",
      "Downloading: 100%|██████████| 64.2k/64.2k [00:00<00:00, 988kB/s]\n",
      "Downloading: 100%|██████████| 55.6k/55.6k [00:00<00:00, 1.10MB/s]\n",
      "Downloading: 100%|██████████| 2.64k/2.64k [00:00<00:00, 13.3MB/s]\n",
      "Downloading: 100%|██████████| 214/214 [00:00<00:00, 635kB/s]\n",
      "Downloading: 100%|██████████| 2.44M/2.44M [00:00<00:00, 11.3MB/s]\n",
      "Downloading: 100%|██████████| 14.3k/14.3k [00:00<00:00, 533kB/s]\n",
      "Downloading: 100%|██████████| 27.4k/27.4k [00:00<00:00, 862kB/s]\n",
      "Downloading: 100%|██████████| 8.25k/8.25k [00:00<00:00, 11.9MB/s]\n",
      "Downloading: 100%|██████████| 193/193 [00:00<00:00, 1.21MB/s]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "from modelscope.hub.snapshot_download import snapshot_download\n",
    "from pathlib import Path\n",
    "\n",
    "local_model_path = Path(\"./LLM_qwen_int4_model\")\n",
    "\n",
    "local_model_path.mkdir(exist_ok=True)\n",
    "model_name = \"qwen/Qwen-7B-Chat-Int4\"\n",
    "commit_hash = \"v1.1.4\"\n",
    "\n",
    "snapshot_download(model_name, revision=commit_hash, cache_dir=local_model_path)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d666c79-b039-4258-ac3b-46b19e63c3b8",
   "metadata": {},
   "source": [
    "### 2. 把模型拷贝到S3为后续部署做准备"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "e9431deb-6359-442d-847b-1563f8dd3854",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sagemaker.config INFO - Not applying SDK defaults from location: /etc/xdg/sagemaker/config.yaml\n",
      "sagemaker.config INFO - Not applying SDK defaults from location: /root/.config/sagemaker/config.yaml\n",
      "sagemaker.config INFO - Not applying SDK defaults from location: /etc/xdg/sagemaker/config.yaml\n",
      "sagemaker.config INFO - Not applying SDK defaults from location: /root/.config/sagemaker/config.yaml\n",
      "sagemaker.config INFO - Not applying SDK defaults from location: /etc/xdg/sagemaker/config.yaml\n",
      "sagemaker.config INFO - Not applying SDK defaults from location: /root/.config/sagemaker/config.yaml\n"
     ]
    }
   ],
   "source": [
    "import sagemaker\n",
    "from sagemaker import image_uris\n",
    "import boto3\n",
    "import os\n",
    "import time\n",
    "import json\n",
    "\n",
    "role = sagemaker.get_execution_role()  # execution role for the endpoint\n",
    "sess = sagemaker.session.Session()  # sagemaker session for interacting with different AWS APIs\n",
    "bucket = sess.default_bucket()  # bucket to house artifacts\n",
    "\n",
    "region = sess._region_name\n",
    "account_id = sess.account_id()\n",
    "\n",
    "s3_client = boto3.client(\"s3\")\n",
    "sm_client = boto3.client(\"sagemaker\")\n",
    "smr_client = boto3.client(\"sagemaker-runtime\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "40dd8f16-ae7c-48bf-8e52-1a15425fa74d",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "s3_code_prefix: LLM-RAG/workshop/LLM_qwen_int4_stream_deploy_code\n",
      "model_snapshot_path: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4\n"
     ]
    }
   ],
   "source": [
    "s3_model_prefix = \"LLM-RAG/workshop/LLM_qwen_int4_stream_model\"  # folder where model checkpoint will go\n",
    "# model_snapshot_path = list(local_model_path.glob(\"**/snapshots/*\"))[0]\n",
    "model_snapshot_path = list(local_model_path.glob(\"**/qwen/*\"))[0]\n",
    "\n",
    "s3_code_prefix = \"LLM-RAG/workshop/LLM_qwen_int4_stream_deploy_code\"\n",
    "print(f\"s3_code_prefix: {s3_code_prefix}\")\n",
    "print(f\"model_snapshot_path: {model_snapshot_path}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "067292c9-c066-4649-a61f-b460a24da584",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/NOTICE to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/NOTICE\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/LICENSE to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/LICENSE\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/.mdl to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/.mdl\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/README.md to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/README.md\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/cpp_kernels.py to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/cpp_kernels.py\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/.msc to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/.msc\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/generation_config.json to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/generation_config.json\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/config.json to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/config.json\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/cache_autogptq_cuda_256.cpp to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/cache_autogptq_cuda_256.cpp\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/configuration_qwen.py to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/configuration_qwen.py\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/cache_autogptq_cuda_kernel_256.cu to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/cache_autogptq_cuda_kernel_256.cu\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/modeling_qwen.py to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/modeling_qwen.py\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/qwen_generation_utils.py to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/qwen_generation_utils.py\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/model.safetensors.index.json to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/model.safetensors.index.json\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/qwen.tiktoken to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/qwen.tiktoken\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/quantize_config.json to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/quantize_config.json\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/tokenization_qwen.py to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/tokenization_qwen.py\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/tokenizer_config.json to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/tokenizer_config.json\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/model-00001-of-00003.safetensors to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/model-00001-of-00003.safetensors\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/model-00002-of-00003.safetensors to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/model-00002-of-00003.safetensors\n",
      "upload: LLM_qwen_int4_model/qwen/Qwen-7B-Chat-Int4/model-00003-of-00003.safetensors to s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/model-00003-of-00003.safetensors\n"
     ]
    }
   ],
   "source": [
    "!aws s3 cp --recursive {model_snapshot_path} s3://{bucket}/{s3_model_prefix}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "696b70c3-90f1-4175-95bf-568bafbcd383",
   "metadata": {},
   "source": [
    "### 3. 模型部署准备（entrypoint脚本，容器镜像，服务配置）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "6f7c4277-4480-42c6-aee6-1fbcca94eb82",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 中国区需要替换为下面的image_uri\n",
    "inference_image_uri = (\n",
    "    f\"727897471807.dkr.ecr.{region}.amazonaws.com.cn/djl-inference:0.23.0-deepspeed0.9.5-cu118\"\n",
    ")\n",
    "\n",
    "# inference_image_uri = image_uris.retrieve(\n",
    "#     framework=\"djl-deepspeed\",\n",
    "#     region=sess.boto_session.region_name,\n",
    "#     version=\"0.23.0\"\n",
    "# )\n",
    "# print(f\"Image going to be used is ---- > {inference_image_uri}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "8d771bdb-11d2-45d2-9bef-face29221838",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "!mkdir -p LLM_qwen_int4_stream_deploy_code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "e5348ecb-43df-4094-97d8-a6723004862a",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing LLM_qwen_int4_stream_deploy_code/model.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile LLM_qwen_int4_stream_deploy_code/model.py\n",
    "from djl_python import Input, Output\n",
    "import torch\n",
    "import logging\n",
    "import math\n",
    "import os\n",
    "\n",
    "from transformers import AutoTokenizer,AutoModelForCausalLM\n",
    "from transformers.generation import GenerationConfig\n",
    "# from auto_gptq import AutoGPTQForCausalLM\n",
    "\n",
    "\n",
    "STOP_flag = \"[DONE]\"\n",
    "\n",
    "\n",
    "def load_model(properties):\n",
    "    tensor_parallel = properties[\"tensor_parallel_degree\"]\n",
    "    model_location = properties['model_dir']\n",
    "    if \"model_id\" in properties:\n",
    "        model_location = properties['model_id']\n",
    "    logging.info(f\"Loading model in {model_location}\")\n",
    "    \n",
    "    tokenizer = AutoTokenizer.from_pretrained(model_location, trust_remote_code=True)\n",
    "    model = AutoModelForCausalLM.from_pretrained(model_location, device_map=\"auto\", trust_remote_code=True).eval()\n",
    "    model.generation_config  = GenerationConfig.from_pretrained(model_location, trust_remote_code=True) # 可指定不同的生成长度、top_p等相关超参\n",
    "    return model, tokenizer, model.generation_config \n",
    "\n",
    "\n",
    "model = None\n",
    "tokenizer = None\n",
    "generator = None\n",
    "config = None\n",
    "\n",
    "def stream_items(prompt, history, max_length, top_p, temperature):\n",
    "    global model, tokenizer, config\n",
    "    size = 0\n",
    "    response = \"\"\n",
    "    config.max_new_tokens = max_length\n",
    "    config.top_p = top_p\n",
    "    \n",
    "    ##传入temperature会报错\n",
    "    ##model.generation_config.temperature = temperature \n",
    "    res_generator = model.chat_stream(tokenizer, prompt, history=history,generation_config=config)\n",
    "    for response in res_generator:\n",
    "        this_response = response[size:]\n",
    "        size = len(response)\n",
    "        stream_buffer = { \"outputs\":this_response,\"finished\": False}\n",
    "        yield stream_buffer\n",
    "    ## stop\n",
    "    # yield {\"query\": prompt, \"outputs\": STOP_flag, \"response\": response, \"history\": [], \"finished\": True}\n",
    "\n",
    "\n",
    "def handle(inputs: Input):\n",
    "    global model, tokenizer,config\n",
    "    if not model:\n",
    "        model, tokenizer,config = load_model(inputs.get_properties())\n",
    "\n",
    "    if inputs.is_empty():\n",
    "        return None\n",
    "    data = inputs.get_as_json()\n",
    "    \n",
    "    input_sentences = data[\"inputs\"]\n",
    "    params = data[\"parameters\"]\n",
    "    history = data.get(\"history\",[])\n",
    "    stream = data.get('stream',False)\n",
    "    print(f'input prompt:{input_sentences}')   \n",
    "    outputs = Output()\n",
    "    if stream:\n",
    "        outputs.add_property(\"content-type\", \"application/jsonlines\")\n",
    "        outputs.add_stream_content(stream_items(input_sentences,history=history,**params))\n",
    "    else:\n",
    "        config.max_new_tokens = params.get('max_length',1024)\n",
    "        config.top_p = params.get('top_p',1)\n",
    "        response, history = model.chat(tokenizer, input_sentences, history=history,generation_config=config)\n",
    "        result = {\"outputs\": response, \"history\" : history}\n",
    "        outputs.add_as_json(result)\n",
    "        \n",
    "    return outputs"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a06d1e60-3914-4059-a08f-05ac26761165",
   "metadata": {},
   "source": [
    "#### Note: option.s3url 需要按照自己的账号进行修改"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "8996fe44-8e70-468b-abc1-38187cb33f4f",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting LLM_qwen_int4_stream_deploy_code/serving.properties\n"
     ]
    }
   ],
   "source": [
    "%%writefile LLM_qwen_int4_stream_deploy_code/serving.properties\n",
    "engine=Python\n",
    "option.tensor_parallel_degree=1\n",
    "option.enable_streaming=True\n",
    "option.predict_timeout=240\n",
    "option.s3url = s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_model/"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "feef22a2-27b9-4018-a46b-6a99b532512f",
   "metadata": {},
   "source": [
    "#### 注意: 必须把transformers升级到4.27.1以上，否则会出现 [Issue344](https://github.com/THUDM/ChatGLM-6B/issues/344)\n",
    "\n",
    "如果是中国区建议添加国内的pip镜像,如下代码所示\n",
    "```\n",
    "%%writefile LLM_chatglm_deploy_code/requirements.txt\n",
    "-i https://pypi.tuna.tsinghua.edu.cn/simple\n",
    "transformers==4.28.1\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "7b7e76c6-6dbc-47fc-9f47-4765c526ab76",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting LLM_qwen_int4_stream_deploy_code/requirements.txt\n"
     ]
    }
   ],
   "source": [
    "%%writefile LLM_qwen_int4_stream_deploy_code/requirements.txt\n",
    "-i https://pypi.tuna.tsinghua.edu.cn/simple\n",
    "transformers==4.32.0\n",
    "accelerate\n",
    "tiktoken\n",
    "einops\n",
    "scipy\n",
    "transformers_stream_generator==0.0.4\n",
    "peft\n",
    "deepspeed\n",
    "auto-gptq\n",
    "optimum"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "199907e8-dde4-43b5-a6f3-82f46a6bf6f3",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# !pip install auto-gptq"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "0ae6734a-aacd-410d-818d-0a962697c3c4",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "LLM_qwen_int4_stream_deploy_code/\n",
      "LLM_qwen_int4_stream_deploy_code/model.py\n",
      "LLM_qwen_int4_stream_deploy_code/requirements.txt\n",
      "LLM_qwen_int4_stream_deploy_code/serving.properties\n"
     ]
    }
   ],
   "source": [
    "!rm model.tar.gz\n",
    "!cd LLM_qwen_int4_stream_deploy_code && rm -rf \".ipynb_checkpoints\"\n",
    "!tar czvf model.tar.gz LLM_qwen_int4_stream_deploy_code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "0f77dc76-6d8c-4665-ba88-f03e887c136c",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "S3 Code or Model tar ball uploaded to --- > s3://sagemaker-cn-northwest-1-370400458231/LLM-RAG/workshop/LLM_qwen_int4_stream_deploy_code/model.tar.gz\n"
     ]
    }
   ],
   "source": [
    "s3_code_artifact = sess.upload_data(\"model.tar.gz\", bucket, s3_code_prefix)\n",
    "print(f\"S3 Code or Model tar ball uploaded to --- > {s3_code_artifact}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5853daa-b8a3-4485-8c0a-64bf83e93a18",
   "metadata": {},
   "source": [
    "### 4. 创建模型 & 创建endpoint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "ef974ca1-9638-45a8-9145-ea9d03b2b072",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "qwen-stream-int4-2023-10-08-09-22-02-560\n",
      "Image going to be used is ---- > 727897471807.dkr.ecr.cn-northwest-1.amazonaws.com.cn/djl-inference:0.23.0-deepspeed0.9.5-cu118\n",
      "Created Model: arn:aws-cn:sagemaker:cn-northwest-1:370400458231:model/qwen-stream-int4-2023-10-08-09-22-02-560\n"
     ]
    }
   ],
   "source": [
    "from sagemaker.utils import name_from_base\n",
    "import boto3\n",
    "\n",
    "model_name = name_from_base(f\"qwen-stream-int4\") #Note: Need to specify model_name\n",
    "print(model_name)\n",
    "print(f\"Image going to be used is ---- > {inference_image_uri}\")\n",
    "\n",
    "create_model_response = sm_client.create_model(\n",
    "    ModelName=model_name,\n",
    "    ExecutionRoleArn=role,\n",
    "    PrimaryContainer={\n",
    "        \"Image\": inference_image_uri,\n",
    "        \"ModelDataUrl\": s3_code_artifact\n",
    "    },\n",
    "    \n",
    ")\n",
    "model_arn = create_model_response[\"ModelArn\"]\n",
    "\n",
    "print(f\"Created Model: {model_arn}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "233bb3a4-d737-41ad-8fcc-7082c6278e8c",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'EndpointConfigArn': 'arn:aws-cn:sagemaker:cn-northwest-1:370400458231:endpoint-config/qwen-stream-int4-2023-10-08-09-22-02-560-config',\n",
       " 'ResponseMetadata': {'RequestId': 'bc8744a9-9231-4b63-b693-5f69ed30f9e0',\n",
       "  'HTTPStatusCode': 200,\n",
       "  'HTTPHeaders': {'x-amzn-requestid': 'bc8744a9-9231-4b63-b693-5f69ed30f9e0',\n",
       "   'content-type': 'application/x-amz-json-1.1',\n",
       "   'content-length': '136',\n",
       "   'date': 'Sun, 08 Oct 2023 09:22:04 GMT'},\n",
       "  'RetryAttempts': 0}}"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "endpoint_config_name = f\"{model_name}-config\"\n",
    "endpoint_name = f\"{model_name}-endpoint\"\n",
    "\n",
    "#Note: ml.g4dn.2xlarge 也可以选择\n",
    "endpoint_config_response = sm_client.create_endpoint_config(\n",
    "    EndpointConfigName=endpoint_config_name,\n",
    "    ProductionVariants=[\n",
    "        {\n",
    "            \"VariantName\": \"variant1\",\n",
    "            \"ModelName\": model_name,\n",
    "            \"InstanceType\": \"ml.g4dn.2xlarge\",\n",
    "            \"InitialInstanceCount\": 1,\n",
    "            # \"VolumeSizeInGB\" : 400,\n",
    "            # \"ModelDataDownloadTimeoutInSeconds\": 2400,\n",
    "            \"ContainerStartupHealthCheckTimeoutInSeconds\": 15*60,\n",
    "        },\n",
    "    ],\n",
    ")\n",
    "endpoint_config_response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "734a39b0-473e-4421-94c8-74d2b4105038",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Created Endpoint: arn:aws-cn:sagemaker:cn-northwest-1:370400458231:endpoint/qwen-stream-int4-2023-10-08-09-22-02-560-endpoint\n"
     ]
    }
   ],
   "source": [
    "create_endpoint_response = sm_client.create_endpoint(\n",
    "    EndpointName=f\"{endpoint_name}\", EndpointConfigName=endpoint_config_name\n",
    ")\n",
    "print(f\"Created Endpoint: {create_endpoint_response['EndpointArn']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1262e826-a810-401d-a5a9-f62febb24e5f",
   "metadata": {},
   "source": [
    "#### 持续检测模型部署进度"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "08969928-6b9e-4d9c-a033-a31f5f77bdfb",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Status: Creating\n",
      "Status: Creating\n",
      "Status: Creating\n",
      "Status: Creating\n",
      "Status: Creating\n",
      "Status: Creating\n",
      "Status: InService\n",
      "Arn: arn:aws-cn:sagemaker:cn-northwest-1:370400458231:endpoint/qwen-stream-int4-2023-10-08-09-22-02-560-endpoint\n",
      "Status: InService\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "resp = sm_client.describe_endpoint(EndpointName=endpoint_name)\n",
    "status = resp[\"EndpointStatus\"]\n",
    "print(\"Status: \" + status)\n",
    "\n",
    "while status == \"Creating\":\n",
    "    time.sleep(60)\n",
    "    resp = sm_client.describe_endpoint(EndpointName=endpoint_name)\n",
    "    status = resp[\"EndpointStatus\"]\n",
    "    print(\"Status: \" + status)\n",
    "\n",
    "print(\"Arn: \" + resp[\"EndpointArn\"])\n",
    "print(\"Status: \" + status)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d985b427-3959-46f7-9a50-5a2b45e2d513",
   "metadata": {},
   "source": [
    "### 5. 模型测试"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "e56bfdaa-3469-4784-aa8a-e32177cde3f2",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 4 ms, sys: 0 ns, total: 4 ms\n",
      "Wall time: 3.89 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "import json\n",
    "import boto3\n",
    "\n",
    "smr_client = boto3.client(\"sagemaker-runtime\")\n",
    "\n",
    "parameters = {\n",
    "  \"max_length\": 1024,\n",
    "  \"temperature\": 0.1,\n",
    "  \"top_p\":0.8\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "ae5983aa-0c91-4c78-a63f-7192a39a8cfb",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import io\n",
    "\n",
    "\n",
    "class StreamScanner:\n",
    "    \"\"\"\n",
    "    A helper class for parsing the InvokeEndpointWithResponseStream event stream. \n",
    "    \n",
    "    The output of the model will be in the following format:\n",
    "    ```\n",
    "    b'{\"outputs\": [\" a\"]}\\n'\n",
    "    b'{\"outputs\": [\" challenging\"]}\\n'\n",
    "    b'{\"outputs\": [\" problem\"]}\\n'\n",
    "    ...\n",
    "    ```\n",
    "    \n",
    "    While usually each PayloadPart event from the event stream will contain a byte array \n",
    "    with a full json, this is not guaranteed and some of the json objects may be split across\n",
    "    PayloadPart events. For example:\n",
    "    ```\n",
    "    {'PayloadPart': {'Bytes': b'{\"outputs\": '}}\n",
    "    {'PayloadPart': {'Bytes': b'[\" problem\"]}\\n'}}\n",
    "    ```\n",
    "    \n",
    "    This class accounts for this by concatenating bytes written via the 'write' function\n",
    "    and then exposing a method which will return lines (ending with a '\\n' character) within\n",
    "    the buffer via the 'readlines' function. It maintains the position of the last read \n",
    "    position to ensure that previous bytes are not exposed again. \n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        self.buff = io.BytesIO()\n",
    "        self.read_pos = 0\n",
    "        \n",
    "    def write(self, content):\n",
    "        self.buff.seek(0, io.SEEK_END)\n",
    "        self.buff.write(content)\n",
    "        \n",
    "    def readlines(self):\n",
    "        self.buff.seek(self.read_pos)\n",
    "        for line in self.buff.readlines():\n",
    "            if line[-1] != b'\\n':\n",
    "                self.read_pos += len(line)\n",
    "                yield line[:-1]\n",
    "                \n",
    "    def reset(self):\n",
    "        self.read_pos = 0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad367ddf-96b6-40e1-938e-2a9aa0f03b0c",
   "metadata": {},
   "source": [
    "## Stream"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "84f9219f-fa4d-413e-b02d-2047142b4a79",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你好！有什么我能为你效劳的吗？\n",
      "time:1.3518805503845215 s\n"
     ]
    }
   ],
   "source": [
    "# prompts1 = \"\"\"你\"\"\"\n",
    "import time\n",
    "\n",
    "start = time.time()\n",
    "prompts1 = \"\"\"写一篇500字的科幻小说，背景关于宇宙战争\"\"\"\n",
    "prompts1 = \"\"\"AWS Clean Rooms 的FAQ文档有提到 Q: 是否发起者和数据贡献者都会被收费？A: 是单方收费，只有查询的接收方会收费。\n",
    "请问AWS Clean Rooms是多方都会收费吗？\n",
    "\"\"\"\n",
    "prompts1 = \"\"\"你好\"\"\"\n",
    "response_model = smr_client.invoke_endpoint_with_response_stream(\n",
    "            EndpointName=endpoint_name,\n",
    "            Body=json.dumps(\n",
    "            {\n",
    "                \"inputs\": prompts1,\n",
    "                \"parameters\": parameters,\n",
    "                \"history\" : [],\n",
    "                \"stream\" : True,\n",
    "            }\n",
    "            ),\n",
    "            ContentType=\"application/json\",\n",
    "        )\n",
    "\n",
    "event_stream = response_model['Body']\n",
    "scanner = StreamScanner()\n",
    "for event in event_stream:\n",
    "    scanner.write(event['PayloadPart']['Bytes'])\n",
    "    for line in scanner.readlines():\n",
    "        try:\n",
    "            resp = json.loads(line)\n",
    "            # print(resp)\n",
    "            print(resp.get(\"outputs\")['outputs'], end='')\n",
    "        except Exception as e:\n",
    "            print(line)\n",
    "            continue\n",
    "print (f\"\\ntime:{time.time()-start} s\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "619db19b-0072-4d25-a4df-5d59c2f6947b",
   "metadata": {},
   "source": [
    "## None stream"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "d577e076-52b2-4257-a447-1d3a5813d7ce",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"outputs\":\"1000b＞1000t\",\n",
      "  \"history\":[\n",
      "    [\n",
      "      \"你现在是口袋奇兵(TopWar:Battle Game)的专属智能客服TopWarBot，你是一个非常专业的游戏客服，，请严格确理解的根据反引号中的资料提取相关信息，回答指挥官的各种问题，不可联想推测反引号中没有的信息,不可提供带有岐义和模棱两可的回答。\\n```\\n问题: 钛蓝金币转换成钻石的比例\\n回答: 按照1：1的比例i进行转换，1个钛蓝金币=1个钻石\\n\\n问题: 金币\\n回答: 1、金币的定义：金币是《口袋奇兵》世界中的通用货币\\n2、金币的获得方法：在游戏内可以通过税收中心/金币收割机进行获取。需要放置金矿生产金币，同时有部分装饰是可以提高金币产量。税收中心只需要20个当前玩家等级民居即可达到之前造满民居的收益。新版本的金币自动收割机是需要10个当前等级的金矿。\\n3、金币的用途：建筑升级、装备制造与改造等大部分游戏功能均需要消耗一定数量的金币\\n\\n问题: 远征行动中如何查看小地图与大地图\\n回答: 在远征行动主页面点击游戏正上方的小地图，可以查看当前关卡的信息，在点击右上角的“地图”就可以观看远征行动大地图信息\\n\\n问题: 数值单位\\n回答: 游戏的数值显示单位为\\nk→m→b→t→aa→bb→cc→dd→ee→ff→gg→hh依次递进，1000进一个单位，比如1000=1k，1000k=1m，1000m=1b，1000b=1t，1000t=1aa，1000aa=1bb，1000bb=1cc。\\n```\\n\\n指挥官: 金币单位t大还是b大\\nTopWarBot: \\n\",\n",
      "      \"1000b＞1000t\"\n",
      "    ]\n",
      "  ]\n",
      "}\n",
      "\n",
      "time:1.2766568660736084 s\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "parameters = {\n",
    "  \"max_length\": 1024,\n",
    "  \"temperature\": 0.1,\n",
    "  \"top_p\":0.8\n",
    "}\n",
    "\n",
    "# prompts1 = \"\"\"AWS Clean Rooms 的FAQ文档有提到 Q: 是否发起者和数据贡献者都会被收费？A: 是单方收费，只有查询的接收方会收费。\n",
    "# 请问AWS Clean Rooms是多方都会收费吗？\n",
    "# \"\"\"\n",
    "\n",
    "prompts1 = \"\"\"你现在是口袋奇兵(TopWar:Battle Game)的专属智能客服TopWarBot，你是一个非常专业的游戏客服，，请严格确理解的根据反引号中的资料提取相关信息，回答指挥官的各种问题，不可联想推测反引号中没有的信息,不可提供带有岐义和模棱两可的回答。\n",
    "```\n",
    "问题: 钛蓝金币转换成钻石的比例\n",
    "回答: 按照1：1的比例i进行转换，1个钛蓝金币=1个钻石\n",
    "\n",
    "问题: 金币\n",
    "回答: 1、金币的定义：金币是《口袋奇兵》世界中的通用货币\n",
    "2、金币的获得方法：在游戏内可以通过税收中心/金币收割机进行获取。需要放置金矿生产金币，同时有部分装饰是可以提高金币产量。税收中心只需要20个当前玩家等级民居即可达到之前造满民居的收益。新版本的金币自动收割机是需要10个当前等级的金矿。\n",
    "3、金币的用途：建筑升级、装备制造与改造等大部分游戏功能均需要消耗一定数量的金币\n",
    "\n",
    "问题: 远征行动中如何查看小地图与大地图\n",
    "回答: 在远征行动主页面点击游戏正上方的小地图，可以查看当前关卡的信息，在点击右上角的“地图”就可以观看远征行动大地图信息\n",
    "\n",
    "问题: 数值单位\n",
    "回答: 游戏的数值显示单位为\n",
    "k→m→b→t→aa→bb→cc→dd→ee→ff→gg→hh依次递进，1000进一个单位，比如1000=1k，1000k=1m，1000m=1b，1000b=1t，1000t=1aa，1000aa=1bb，1000bb=1cc。\n",
    "```\n",
    "\n",
    "指挥官: 金币单位t大还是b大\n",
    "TopWarBot: \n",
    "\"\"\"\n",
    "\n",
    "prompts2 = \"\"\"你好\"\"\"\n",
    "start = time.time()\n",
    "\n",
    "response_model = smr_client.invoke_endpoint(\n",
    "            EndpointName=endpoint_name,\n",
    "            Body=json.dumps(\n",
    "            {\n",
    "                \"inputs\": prompts1,\n",
    "                \"parameters\": parameters,\n",
    "                \"history\" : [],\n",
    "            }\n",
    "            ),\n",
    "            ContentType=\"application/json\",\n",
    "        )\n",
    "\n",
    "print(response_model['Body'].read().decode('utf8'))\n",
    "print (f\"\\ntime:{time.time()-start} s\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4413d305-72fa-4c55-914d-3e205cb56cf7",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "21c8b703-e312-4964-8be9-a754468e07cd",
   "metadata": {},
   "source": [
    "#### 清除模型Endpoint和config"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "f70d116f-4fb1-4f04-8732-3d6e4fb520de",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "An error occurred (ValidationException) when calling the DeleteEndpoint operation: Could not find endpoint \"qwen-stream-int4-2023-10-08-08-55-00-416-endpoint\".\n"
     ]
    }
   ],
   "source": [
    "!aws sagemaker delete-endpoint --endpoint-name {endpoint_name}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "184e4d1d-3d62-43df-9b17-5d64ece928bd",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "An error occurred (ValidationException) when calling the DeleteEndpointConfig operation: Could not find endpoint configuration \"qwen-stream-int4-2023-10-08-08-55-00-416-config\".\n"
     ]
    }
   ],
   "source": [
    "!aws sagemaker delete-endpoint-config --endpoint-config-name {endpoint_config_name}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "707e8f09",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "An error occurred (ValidationException) when calling the DeleteModel operation: Could not find model \"qwen-stream-int4-2023-10-08-08-55-00-416\".\n"
     ]
    }
   ],
   "source": [
    "!aws sagemaker delete-model --model-name {model_name}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a2890ad5-2db4-4410-be1a-5f71322f57ea",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "availableInstances": [
   {
    "_defaultOrder": 0,
    "_isFastLaunch": true,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 4,
    "name": "ml.t3.medium",
    "vcpuNum": 2
   },
   {
    "_defaultOrder": 1,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 8,
    "name": "ml.t3.large",
    "vcpuNum": 2
   },
   {
    "_defaultOrder": 2,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 16,
    "name": "ml.t3.xlarge",
    "vcpuNum": 4
   },
   {
    "_defaultOrder": 3,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 32,
    "name": "ml.t3.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 4,
    "_isFastLaunch": true,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 8,
    "name": "ml.m5.large",
    "vcpuNum": 2
   },
   {
    "_defaultOrder": 5,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 16,
    "name": "ml.m5.xlarge",
    "vcpuNum": 4
   },
   {
    "_defaultOrder": 6,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 32,
    "name": "ml.m5.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 7,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 64,
    "name": "ml.m5.4xlarge",
    "vcpuNum": 16
   },
   {
    "_defaultOrder": 8,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 128,
    "name": "ml.m5.8xlarge",
    "vcpuNum": 32
   },
   {
    "_defaultOrder": 9,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 192,
    "name": "ml.m5.12xlarge",
    "vcpuNum": 48
   },
   {
    "_defaultOrder": 10,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 256,
    "name": "ml.m5.16xlarge",
    "vcpuNum": 64
   },
   {
    "_defaultOrder": 11,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 384,
    "name": "ml.m5.24xlarge",
    "vcpuNum": 96
   },
   {
    "_defaultOrder": 12,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 8,
    "name": "ml.m5d.large",
    "vcpuNum": 2
   },
   {
    "_defaultOrder": 13,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 16,
    "name": "ml.m5d.xlarge",
    "vcpuNum": 4
   },
   {
    "_defaultOrder": 14,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 32,
    "name": "ml.m5d.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 15,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 64,
    "name": "ml.m5d.4xlarge",
    "vcpuNum": 16
   },
   {
    "_defaultOrder": 16,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 128,
    "name": "ml.m5d.8xlarge",
    "vcpuNum": 32
   },
   {
    "_defaultOrder": 17,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 192,
    "name": "ml.m5d.12xlarge",
    "vcpuNum": 48
   },
   {
    "_defaultOrder": 18,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 256,
    "name": "ml.m5d.16xlarge",
    "vcpuNum": 64
   },
   {
    "_defaultOrder": 19,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 384,
    "name": "ml.m5d.24xlarge",
    "vcpuNum": 96
   },
   {
    "_defaultOrder": 20,
    "_isFastLaunch": false,
    "category": "General purpose",
    "gpuNum": 0,
    "hideHardwareSpecs": true,
    "memoryGiB": 0,
    "name": "ml.geospatial.interactive",
    "supportedImageNames": [
     "sagemaker-geospatial-v1-0"
    ],
    "vcpuNum": 0
   },
   {
    "_defaultOrder": 21,
    "_isFastLaunch": true,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 4,
    "name": "ml.c5.large",
    "vcpuNum": 2
   },
   {
    "_defaultOrder": 22,
    "_isFastLaunch": false,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 8,
    "name": "ml.c5.xlarge",
    "vcpuNum": 4
   },
   {
    "_defaultOrder": 23,
    "_isFastLaunch": false,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 16,
    "name": "ml.c5.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 24,
    "_isFastLaunch": false,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 32,
    "name": "ml.c5.4xlarge",
    "vcpuNum": 16
   },
   {
    "_defaultOrder": 25,
    "_isFastLaunch": false,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 72,
    "name": "ml.c5.9xlarge",
    "vcpuNum": 36
   },
   {
    "_defaultOrder": 26,
    "_isFastLaunch": false,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 96,
    "name": "ml.c5.12xlarge",
    "vcpuNum": 48
   },
   {
    "_defaultOrder": 27,
    "_isFastLaunch": false,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 144,
    "name": "ml.c5.18xlarge",
    "vcpuNum": 72
   },
   {
    "_defaultOrder": 28,
    "_isFastLaunch": false,
    "category": "Compute optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 192,
    "name": "ml.c5.24xlarge",
    "vcpuNum": 96
   },
   {
    "_defaultOrder": 29,
    "_isFastLaunch": true,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 16,
    "name": "ml.g4dn.xlarge",
    "vcpuNum": 4
   },
   {
    "_defaultOrder": 30,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 32,
    "name": "ml.g4dn.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 31,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 64,
    "name": "ml.g4dn.4xlarge",
    "vcpuNum": 16
   },
   {
    "_defaultOrder": 32,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 128,
    "name": "ml.g4dn.8xlarge",
    "vcpuNum": 32
   },
   {
    "_defaultOrder": 33,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 4,
    "hideHardwareSpecs": false,
    "memoryGiB": 192,
    "name": "ml.g4dn.12xlarge",
    "vcpuNum": 48
   },
   {
    "_defaultOrder": 34,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 256,
    "name": "ml.g4dn.16xlarge",
    "vcpuNum": 64
   },
   {
    "_defaultOrder": 35,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 61,
    "name": "ml.p3.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 36,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 4,
    "hideHardwareSpecs": false,
    "memoryGiB": 244,
    "name": "ml.p3.8xlarge",
    "vcpuNum": 32
   },
   {
    "_defaultOrder": 37,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 8,
    "hideHardwareSpecs": false,
    "memoryGiB": 488,
    "name": "ml.p3.16xlarge",
    "vcpuNum": 64
   },
   {
    "_defaultOrder": 38,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 8,
    "hideHardwareSpecs": false,
    "memoryGiB": 768,
    "name": "ml.p3dn.24xlarge",
    "vcpuNum": 96
   },
   {
    "_defaultOrder": 39,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 16,
    "name": "ml.r5.large",
    "vcpuNum": 2
   },
   {
    "_defaultOrder": 40,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 32,
    "name": "ml.r5.xlarge",
    "vcpuNum": 4
   },
   {
    "_defaultOrder": 41,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 64,
    "name": "ml.r5.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 42,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 128,
    "name": "ml.r5.4xlarge",
    "vcpuNum": 16
   },
   {
    "_defaultOrder": 43,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 256,
    "name": "ml.r5.8xlarge",
    "vcpuNum": 32
   },
   {
    "_defaultOrder": 44,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 384,
    "name": "ml.r5.12xlarge",
    "vcpuNum": 48
   },
   {
    "_defaultOrder": 45,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 512,
    "name": "ml.r5.16xlarge",
    "vcpuNum": 64
   },
   {
    "_defaultOrder": 46,
    "_isFastLaunch": false,
    "category": "Memory Optimized",
    "gpuNum": 0,
    "hideHardwareSpecs": false,
    "memoryGiB": 768,
    "name": "ml.r5.24xlarge",
    "vcpuNum": 96
   },
   {
    "_defaultOrder": 47,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 16,
    "name": "ml.g5.xlarge",
    "vcpuNum": 4
   },
   {
    "_defaultOrder": 48,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 32,
    "name": "ml.g5.2xlarge",
    "vcpuNum": 8
   },
   {
    "_defaultOrder": 49,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 64,
    "name": "ml.g5.4xlarge",
    "vcpuNum": 16
   },
   {
    "_defaultOrder": 50,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 128,
    "name": "ml.g5.8xlarge",
    "vcpuNum": 32
   },
   {
    "_defaultOrder": 51,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 1,
    "hideHardwareSpecs": false,
    "memoryGiB": 256,
    "name": "ml.g5.16xlarge",
    "vcpuNum": 64
   },
   {
    "_defaultOrder": 52,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 4,
    "hideHardwareSpecs": false,
    "memoryGiB": 192,
    "name": "ml.g5.12xlarge",
    "vcpuNum": 48
   },
   {
    "_defaultOrder": 53,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 4,
    "hideHardwareSpecs": false,
    "memoryGiB": 384,
    "name": "ml.g5.24xlarge",
    "vcpuNum": 96
   },
   {
    "_defaultOrder": 54,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 8,
    "hideHardwareSpecs": false,
    "memoryGiB": 768,
    "name": "ml.g5.48xlarge",
    "vcpuNum": 192
   },
   {
    "_defaultOrder": 55,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 8,
    "hideHardwareSpecs": false,
    "memoryGiB": 1152,
    "name": "ml.p4d.24xlarge",
    "vcpuNum": 96
   },
   {
    "_defaultOrder": 56,
    "_isFastLaunch": false,
    "category": "Accelerated computing",
    "gpuNum": 8,
    "hideHardwareSpecs": false,
    "memoryGiB": 1152,
    "name": "ml.p4de.24xlarge",
    "vcpuNum": 96
   }
  ],
  "instance_type": "ml.m5.large",
  "kernelspec": {
   "display_name": "Python 3 (Data Science 3.0)",
   "language": "python",
   "name": "python3__SAGEMAKER_INTERNAL__arn:aws-cn:sagemaker:cn-northwest-1:390780980154:image/sagemaker-data-science-310-v1"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
